<?php

namespace App\Http\Controllers\Api\MiniprogramToGame;

use App\Http\Controllers\Controller;
use App\Models\Log\LogWxMiniprogramJumpgame;
use App\Models\WxMiniprogramConfig;
use App\Services\MiniprogramToGame\MiniprogramToGameService;
use App\Services\MiniprogramToGame\PokemonVoteService;
use App\Services\WechatService;
use Illuminate\Http\Request;

class StartController extends Controller
{
    public function index(Request $request)
    {
        $appid        = $request->input('appid');
        $access_token = $request->input('access_token');
        $launch_info  = $request->input('launch_info');
        $path         = $request->input('path')??'';

        $mini = WxMiniprogramConfig::where('appid', $appid)->first();
        if (!$mini) {
            return yqerr(6045);
        }

        $ret = WechatService::getInstance()->code2Session($appid, $mini->secret, $access_token);
        if (!$ret || (isset($ret['errcode']) && $ret['errcode'] !== 0)) {
            return yqerr(6026);
        }

        $openid      = $ret['openid'];
        $unionid     = $ret['unionid'] ?? '';
        $launch_info = json_decode($launch_info, true);
        $scene       = $launch_info['scene'];
        $querys      = $launch_info['query'];
        // 如果是从其他小程序跳转过来，将信息整合到 query
        if (!empty($launch_info['referrerInfo'])) {
            $querys['referrer_appid'] = $launch_info['referrerInfo']['appId'] ?? '';
            $extra = $launch_info['referrerInfo']['extraData'] ?? [];
            if (!empty($extra)) {
                $querys = array_merge($querys, $extra);
            }
        }

        $data            = MiniprogramToGameService::getInstance()->getStartInfo($appid, $openid, $scene, $querys, $launch_info);
        $data['type']    = $data['type'] ?? 0;
        $data['openid']  = $openid;
        $data['unionid'] = $unionid;

        // 如果是跳转到path，而且path跟初始化时的path一致，则无需跳转
        if ($data['type'] == LogWxMiniprogramJumpgame::JUMP_TYPE_PAGE) {
            $path = "/" . $path;
            if ($data['page']['path'] == $path) {
                $data['type'] = 0;
            }
        }

        // 如果是首次打开，则随机给他添加一个投票数据
        $is_first = $data['is_first'] ?? false;
        if ($is_first) {
            $item_id = rand(1, 10);
            PokemonVoteService::getInstance()->userVote($appid, $item_id);
        }

        return yqok($data);
    }
}
